package com.zxq.tcp.handler;

import com.zxq.exchange.ExchangeDTO;
import com.zxq.exchange.observer.INotifyDevice;
import com.zxq.tcp.handler.dispatch.TCPDispatchHandler;
import com.zxq.tcp.handler.dispatch.ITcpDispatchHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class TCPDispatchHandlerGatherProxy implements ITcpDispatchHandler, INotifyDevice {

    /**
     * 标志头
     */
    private TCPDispatchHandler head = null;

    /**
     * 标志尾
     */
    private TCPDispatchHandler tail = null;


    /**
     * 添加handler
     * @param item
     */
    public void addHandler(TCPDispatchHandler item) {

        if(head == null) {
            head = item;
            tail = item;
        } else {
            tail.next = item;
            tail = item;
        }

    }


    /**
     * 解析帧数据
     */
    @Override
    public void decodeFrame() {
        head.handlerFrame();
    }

    /**
     * 因为是代理，不调用这个，不处理
     * @return
     */
    @Override
    public boolean isThisFrame() {

        return false;
    }

    /**
     *
     * @param channel 通道
     * @param in 数据信息
     */
    @Override
    public void injectByteBuf(ChannelHandlerContext channel, ByteBuf in) {
        TCPDispatchHandler node = null;
        do{
            node = head;
            if(node != null) {
                node.injectByteBuf(channel,in);
            }
            node = head.next;
        } while (node != null);
    }


    @Override
    public void notifyDevice(ExchangeDTO exchangeDTO) {
        TCPDispatchHandler node = null;
        do{
            node = head;
            if(node != null) {
                node.notifyDevice(exchangeDTO);
            }
            node = head.next;
        } while (node != null);
    }

}
